<template>
  <div class="raceRank">
    <div class="r-body">
      <n-spin :show="showSpin" style="--n-opacity-spinning: 0">
        <div class="r-b-head">
          <el-col :span="3">排名</el-col>
          <el-col :span="9">团队名称</el-col>
          <el-col class="score" :span="5">总分</el-col>
          <el-col :span="7">均分</el-col>
        </div>
        <el-collapse v-model="activeName">
          <el-collapse-item v-for="(item, index) in rankList.records" :class="{ 'item-star': item.rank === -1 }"
            :name="index">
            <template #title>
              <div class="e-title">
                <el-col :span="3">
                  <div v-if="item.rank !== -1 && !item.award">
                    {{ item.rank }}
                  </div>
                  <div v-if="item.rank === -1">*</div>
                  <div v-if="item.award !== null && item.award">
                    <el-tooltip class="box-item" effect="dark" :content="awardContent(item)" placement="top">
                      <div class="award" :style="{ background: awardColor(item) }">
                        <i class="iconfont icon-medal"> </i>
                        <div class="rank">
                          {{ item.rank }}
                        </div>
                      </div>
                    </el-tooltip>
                  </div>
                </el-col>
                <el-col :span="9">
                  <n-badge :offset="offset" value="Star" size="small" color="#ffc10a" :show="item.rank === -1">
                    <div class="team">
                      {{ item.name }}
                    </div>
                  </n-badge>
                </el-col>
                <el-col :span="6">
                  <div class="content">
                    <span>
                      {{ item.totalScore }}
                    </span>
                    <span> ({{ item.totalTime }})ms</span>
                  </div>
                </el-col>
                <el-col :span="6">{{ averageScore(item.averageScore) }}</el-col>
              </div>
            </template>
            <div>
              <el-table size="small" class="table" :data="item.oiContestUserRankList" :cell-style="cellStyle">
                <el-table-column prop="displayId" label="用户" width="300px" align="center" class="isStar">
                  <template #default="scoped">
                    <div class="user">
                      <div class="avatar">
                        <n-badge :offset="offset" value="Star" size="small" color="#ffc10a"
                          :show="scoped.row.rank === -1">
                          <el-avatar v-if="scoped.row.avatar === null ||
                            scoped.row.avatar === ''
                          ">{{ scoped.row.username[0] }}</el-avatar>
                          <n-avatar round size="large" :src="$getAvatarUrl(scoped.row.avatar)" v-else />
                        </n-badge>
                      </div>
                      <div>
                        <div class="id">
                          {{ scoped.row.username }}
                        </div>
                        <div>
                          {{ scoped.row.school }}
                        </div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="realName" label="真实姓名" align="center"
                  v-if="rankName === 'realname'"></el-table-column>
                <el-table-column prop="nickname" label="昵称" align="center"
                  v-if="rankName === 'nickname'"></el-table-column>
                <el-table-column prop="totalScore" label="总分" align="center">
                  <template #default="scoped">
                    <div class="t-all">
                      <div class="score">
                        {{ scoped.row.totalScore }}
                      </div>
                      <div class="time">({{ scoped.row.totalTime }}ms)</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column v-for="(item, index) in problem" prop="totalScore" align="center">
                  <template #header>
                    <div class="problem" @click="toProblem(item)">
                      <i :style="{ color: item.color }" class="iconfont icon-icon_qiqiu2"></i>
                      {{ item.displayId }}
                    </div>
                    <div v-if="problemAc[item.pid]">
                      <el-tooltip class="box-item" effect="dark" placement="top">
                        <template #content>
                          <div class="t-title">
                            {{ problem[index].displayId }}.{{
                              problem[index].displayTitle
                            }}
                          </div>
                          <div class="accept">
                            Accepted:&nbsp;{{ problemAc[item.pid].ac }}
                          </div>
                          <div class="reject">
                            Rejected:&nbsp;
                            {{
                              parseInt(problemAc[item.pid].submitCount) -
                            parseInt(problemAc[item.pid].ac)
                            }}
                          </div>
                        </template>
                        <div class="ac">
                          ({{ problemAc[item.pid].ac }}/{{
                            problemAc[item.pid].submitCount
                          }})
                        </div>
                      </el-tooltip>
                    </div>
                  </template>
                  <template #default="scoped">
                    <div class="problemScore" v-if="scoped.row.submissionInfo[item.pid] !== undefined"
                      @click="toStatus(scoped.row.submitIdInfo[item.pid])">
                      <div class="score realScore" :class="{
                        zero:
                          scoped.row.statusInfo[item.pid] !== 0 ||
                          scoped.row.statusInfo[item.pid] !== 1,
                        part: scoped.row.statusInfo[item.pid] === 1,
                        full: scoped.row.statusInfo[item.pid] === 0,
                      }">
                        {{ scoped.row.submissionInfo[item.pid] }}
                      </div>
                      <div class="time">
                        ({{ scoped.row.timeInfo[item.pid] }}ms)
                      </div>
                    </div>
                    <div class="problemScore" v-else>--------</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </n-spin>
    </div>
    <div class="r-foot">
      <el-pagination class="pagination" :page-sizes="[20, 50, 99]" background small layout="prev, pager, next,sizes"
        :page-count="Number(rankList.total)" v-model:current-page="rankParams.pageNum"
        v-model:page-size="rankParams.pageSize" />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, defineProps, toRefs, defineExpose } from "vue";
import useStore from "@/store";
import { useRoute, useRouter } from "vue-router";
import {
  getRaceProblemAPI,
  getRaceProblemAcAPI,
  getRaceProblemScoreAPI,
  getRaceTeamRankAPI,
} from "@/api/ojAPI/ojAPI.js";
import {
  getRaceTeamRankAdminAPI
} from "@/api/adminAPI/adminAPI.js"
import { debounce } from "@/utils/global.js";

const props = defineProps({
  rankName: {
    type: String,
    default: "",
  },
  showStar: {
    type: Boolean,
    default: false,
  },
  showAuto: {
    type: Boolean,
    default: false,
  },
  rankParams: {
    type: Object,
    default: {
      pageSize: 20,
      pageNum: 1,
      searchValue: "",
    },
  },
  awardConfig: {
    type: Array,
    default: [],
  },
  location: {
    tyep: Boolean,
    default: false,
  },
  lockRank: {
    tyep: Boolean,
    default: true,
  },
});
const { rankName, showStar, showAuto, rankParams, location, awardConfig, lockRank } =
  toRefs(props);

onMounted(() => {
  getRaceRank();
  getRaceProblem();
});

const deboundTime = ref(null);
const route = useRoute();
const router = useRouter();
const rankList = ref({
  records: [],
  total: 0,
});

const problem = ref([]);
const problemAc = ref({});
const problemScore = ref({});
const activeName = ref("");
const offset = [-67, 20];
const showSpin = ref(true);
const emit = defineEmits();
const toStatus = (data) => {
  if (location.value) {
    router.push(
      `/home/racePage/${route.params.rid}/evaluation/${data}`
    );
  }
};

// 根据data返回的每一行的数据判断,再修改这一行的样式
const cellStyle = (data) => {
  if (data.row.rank === -1) {
    return {
      background: "#ffffcc",
    };
  }
};
const averageScore = (score) => {
  return parseFloat(score).toFixed(2);
}
const toProblem = (data) => {
  if (location.value) {
    router.push(
      `/home/racePage/${route.params.rid}/problem/${data.pid}?proId=${data.id}`
    );
  }
};
const getRaceRank = () => {
  if (deboundTime.value) {
    clearTimeout(deboundTime.value);
  }
  deboundTime.value = setTimeout(async () => {
    const removeStar = showStar.value ? 1 : 0;
    const data = {
      pageSize: rankParams.value.pageSize,
      pageNum: rankParams.value.pageNum,
      removeStar: removeStar,
      cid: route.params.rid,
      keyword: rankParams.value.searchValue,
    };
    if (lockRank.value) {
      await getRaceTeamRankAPI(data).then((res) => {
        if (res.data.code === 200) {
          rankList.value = res.data.data;
          showSpin.value = false;
        }
      });
    } else {
      await getRaceTeamRankAdminAPI(data).then((res) => {
        if (res.data.code === 200) {
          rankList.value = res.data.data;
          showSpin.value = false;
        }
      });
    }
  });
};
const getRaceProblem = debounce(async () => {
  await getRaceProblemAPI(route.params.rid)
    .then((res) => {
      if (res.data.code === 200) {
        problem.value = res.data.data;
        getRaceProblemAc();
        getRaceProblemScore();
      }
    })
    .catch((err) => {
      console.log(err);
    });
}, 100);
const awardContent = (row) => {
  let name = "";
  for (let i = 0; i < awardConfig.value.length; i++) {
    if (parseInt(awardConfig.value[i].level) === row.award) {
      name = awardConfig.value[i].name;
    }
  }
  return name;
};
const awardColor = (row) => {
  let color = "";
  for (let i = 0; i < awardConfig.value.length; i++) {
    if (parseInt(awardConfig.value[i].level) === row.award) {
      color = awardConfig.value[i].backColor;
    }
  }
  return color;
};
const getRaceProblemAc = debounce(async () => {
  let data = [];
  problem.value.forEach((item) => {
    data.push(item.pid);
  });
  await getRaceProblemAcAPI(route.params.rid, data).then((res) => {
    if (res.data.code === 200) {
      problemAc.value = res.data.data;
    }
  });
}, 100);
const getRaceProblemScore = debounce(async () => {
  let data = [];
  problem.value.forEach((item) => {
    data.push(item.pid);
  });
  await getRaceProblemScoreAPI(route.params.rid, data).then((res) => {
    if (res.data.code === 200) {
      problemScore.value = res.data.data;
    }
  });
}, 100);
defineExpose({ getRaceRank, getRaceProblem });
</script>

<style lang="less" scoped>
.raceRank {
  width: 100%;

  .r-body {
    margin-top: 10px;
    height: 65vh;
    overflow: hidden;
    overflow-y: auto;

    .r-b-head {
      display: flex;
      align-items: center;

      ::v-deep(.el-col) {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #909399;
        padding: 8px 0;
        font-weight: 600;
        margin-right: 1px;
      }

      ::v-deep(.score) {
        margin-left: 10px;
      }
    }

    .e-title {
      width: 100%;
      display: flex;
      align-items: center;

      .award {
        width: 35px;
        height: 35px;
        display: flex;
        margin-left: 6px;
        color: #fff;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;

        .rank {
          font-size: 10px;
        }

        .iconfont {
          font-size: 13px;
        }
      }

      .team {
        font-size: 14px;
        color: #55585ba1;
        font-weight: 550;
      }

      ::v-deep(.el-col) {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #909399;
        padding: 8px 0;
        font-weight: 600;

        .content {
          display: flex;
          flex-direction: column;
          padding-right: 10px;

          span {
            display: flex;
            height: 20px;
            align-items: center;
            justify-content: center;
          }
        }
      }
    }

    .item-star {
      background-color: #ffffcc;
    }

    .table {
      .user {
        display: flex;
        align-items: center;
        justify-content: left;
        padding-left: 50px;

        .avatar {
          display: flex;
          align-items: center;
          margin-right: 10px;
        }

        .id {
          display: flex;
          align-items: center;
        }
      }

      .time {
        font-size: 10px;
        color: #6b6e708f;
        height: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .problem {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        cursor: pointer;

        .iconfont {
          font-size: 12px;
          font-weight: 550;
        }
      }

      .problem:hover {
        color: #18a058;
      }

      .ac {
        font-size: 10px;
      }

      .score {
        font-size: 13px;
      }

      .zero {
        color: rgba(228, 31, 31, 0.83);
        font-weight: 550;
      }

      .part {
        color: #0c61c9a1;
      }

      .full {
        color: #18a058 !important;
      }

      .problemScore {
        font-weight: 600;

        .realScore {
          cursor: pointer;
        }

        .realScore:hover {
          text-decoration: underline;
        }
      }
    }

    .isStar {
      background-color: #ffffcc;
    }

    ::v-deep(.el-collapse-item__wrap) {
      border-top: 1px solid #8f8f8f69;
      margin: 5px 0;
    }
  }

  .r-foot {
    margin: 0 auto;
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }

}

::v-deep(.el-table td:first-child) {
  border-left: 1px solid #e2ecfa;
  border-radius: 10px 0 0 10px;
  padding: 2px;
  background: #fff;
}

::v-deep(.el-table td:last-child) {
  border-right: 1px solid #e2ecfa;
  border-radius: 0 10px 10px 0;
  padding: 2px;
  background: #fff;
}

::v-deep(.el-collapse-item__wrap) {
  border-bottom: none;
}

::v-deep(.item-star) {
  .el-collapse-item__header {
    background-color: #ffffcc;
    border-radius: 20px;
  }
}
</style>
